﻿var PuntoID = 46;
var ComaId = 44;

function NumericFilterOnKeyPressHandler(sender, e)
{
    var keyCode = e.keyCode || e.charCode;
    var esValido = IsValid(keyCode);
    if (IsDecimalSeparator(keyCode))
    {
        if(sender.value.indexOf(",") != -1) return false;
        e.keyCode = ComaId;
        e.charCode = ComaId;
        return true;
    }
    return esValido;
}
       

function NumericFilterOnTextChangeHandler(sender,arg)
{
    var string = sender.value.trim();    
    
    for(var i  = 0; i< string.length; i++)
    {
        var keyCode = string.charCodeAt(i)
        if(!(IsValid(keyCode) || IsDecimalSeparator(keyCode)))
        {
            sender.value = "";
            return false;
        }
    }
    
    sender.value = sender.value.replace(/\./g, ",")
    var punto = sender.value.lastIndexOf(",");
    
    if(punto != -1)
    {
        var decimales = sender.value.slice(punto);
        var enteros = sender.value.slice(0,punto);
        
        sender.value = NumberFormat(enteros.replace(/\,/g, "")) + decimales;
    }
    return true;
 }
 
function NumberFormat(str)
{
    var strArray = str.split('');
    var strResult = '';
    var j = 0;
    for(var i  = strArray.length-1; i >= 0 ; i--)
    {
        strResult = strArray[i] + strResult;
        if(++j % 3 == 0 && i!=0 )strResult = "." + strResult;
    }
    return strResult;
}

 
function IsValid(keyCode)
{
    return keyCode > 47 && keyCode < 58;
}


function IsDecimalSeparator(keyCode)
{
    return keyCode == PuntoID || keyCode == ComaId;
}

$(function()
{

    $("input.input-number").setMask('integer')
    $("input.input-time").setMask('time');
    $("input.input-integer").setMask({mask:'999999999',defaultValue:'0',type: 'reverse'});
    $("input.input-decimal")
        .each(function() { NumericFilterOnTextChangeHandler(this,null); })
        .change(function() { return NumericFilterOnTextChangeHandler(this,null); })
        .keypress(function() { return NumericFilterOnKeyPressHandler(this,event); });
    
});